package com.infodms.dms.actions.claim.basicData;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.bean.AreaProvinceBean;
import com.infodms.dms.bean.PriceAdjustBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.Utility;
import com.infodms.dms.dao.claim.basicData.ClaimBasicLaborPriceDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmDealerPO;
import com.infodms.dms.po.TtAsWrLabourPricePO;
import com.infodms.dms.po.TtAsWrModelGroupPO;
import com.infodms.dms.util.StringUtil;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

/**
 * 索赔工时单价设定
 * @author Administrator
 *
 */

public class ClaimBasicLabourPrice {
	private ActionContext act = null ;
	private RequestWrapper req = null ;
	private AclUserBean user = null ;
	
	private Logger logger = Logger.getLogger(ClaimBasicLabourPrice.class);
	private ClaimBasicLaborPriceDao dao = ClaimBasicLaborPriceDao.getInstance() ;
	
	//轿车
	private final String MAIN_URL = "/jsp/claim/basicData/claimBasicData.jsp" ;
	private final String ADD_URL = "/jsp/claim/basicData/claimBasicDataAdd.jsp" ;
	private final String LABOR_LIST_URL = "/jsp/claim/basicData/laborListSel.jsp" ;
	private final String UPDATE_URL = "/jsp/claim/basicData/claimBasicDataModify.jsp" ; 
	//微车
	private final String WC_MAIN_URL = "/jsp/claim/basicData/claimBasicDataWC.jsp" ;
	private final String WC_MODIFY_URL = "/jsp/claim/basicData/claimBasicDataModifyWC.jsp" ;
	private final String ADJST_URL = "/jsp/claim/basicData/adjustLaborHoursetpre.jsp" ;
	private final String ADJST_MODIFY_URL="/jsp/claim/basicData/adjustModify.jsp";
	
	/*
	 * 索赔工时单价设定主页面初始化
	 */
	public void labourPriceInit(){
		act = ActionContext.getContext() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			List<TtAsWrLabourPricePO> lists = dao.getExistLaborList(user.getCompanyId()) ;
			act.setOutData("lists", lists);
			act.setForword(MAIN_URL);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 索赔工时单价设定新增页面初始化
	 */
	public void labourPriceAddInit(){
		act = ActionContext.getContext() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			List<TtAsWrLabourPricePO> lists = dao.getExistLaborList(user.getCompanyId()) ;
			act.setOutData("list", lists);
			act.setForword(ADD_URL);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定->新增");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 车型大类选择弹出框初始化
	 */
	public void laborListInit(){
		act = ActionContext.getContext() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			act.setForword(LABOR_LIST_URL);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定->工时大类查询");
			logger.error(user, be);
			act.setException(be);
		}
	}

	/*
	 * 车型大类选择弹出框查询主方法
	 */
	public void laborListQuery(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			act.getResponse().setContentType("application/json");
			String code = req.getParamValue("wrgroup_code");
			StringBuffer con = new StringBuffer() ;
			if(StringUtil.notNull(code))
				con.append("and upper(wrgroup_code) like '%").append(code.toUpperCase()).append("%'\n") ;
			con.append("and p.oem_company_id=").append(user.getCompanyId()).append("\n");
			int pageSize = 30 ;
			int curPage = req.getParamValue("curPage") != null ? Integer.parseInt(req.getParamValue("curPage")) : 1; // 处理当前页
			PageResult<TtAsWrModelGroupPO> ps = dao.getLaborList(con.toString(),pageSize, curPage) ;
			act.setOutData("ps", ps);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定->查询");
			logger.error(user, be);
			act.setException(be);
		}
	}

	/*
	 * 索赔工时单价设定新增操作
	 */
	public void laborPriceAdd(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			String dealerId = req.getParamValue("dealer_id");
			String[] laborCodes = req.getParamValues("labor_code");
			String[] prices = req.getParamValues("price");
			
			String[] dealerIds = dealerId.split(",");
			// 向TT_AS_WR_LABOUR_PRICE表中添加数据
			TtAsWrLabourPricePO po = null ;
			for(int i = 0 ; i<dealerIds.length; i++){
				for(int j = 0;j<laborCodes.length;j++){
					if(StringUtil.notNull(prices[j])){
						po = new TtAsWrLabourPricePO() ;
						po.setDealerId(Long.parseLong(dealerIds[i]));
						po.setModeType(laborCodes[j]);
						po = dao.existLaborPrice(po);
						// 此经销商对应的工时大类不存在则执行添加操作
						if(po==null){
							po = new TtAsWrLabourPricePO() ;
							po.setDealerId(Long.parseLong(dealerIds[i]));
							po.setModeType(laborCodes[j]);
							po.setOemCompanyId(user.getCompanyId());
							po.setCreateBy(user.getUserId());
							po.setCreateDate(new Date());
							po.setId(Utility.getLong(SequenceManager.getSequence("")));
							po.setLabourPrice(Double.parseDouble(prices[j]));
							dao.insert(po);
						}else{
							// 此经销商对应的工时大类存在则执行修改操作
							po.setUpdateBy(user.getUserId());
							po.setUpdateDate(new Date());
							po.setLabourPrice(Double.parseDouble(prices[j]));
							TtAsWrLabourPricePO p1 = new TtAsWrLabourPricePO() ;
							p1.setId(po.getId());
							dao.update(p1, po);
						}
					}
				}
			}
			this.labourPriceInit();
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.ADD_FAILURE_CODE, "索赔基本参数设定->新增");
			logger.error(user, be);
			act.setException(be);
		}
	}

	/*
	 * 索赔工时单价设定主页面第一次主查询
	 */
	public void laborPriceMainQuery(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			String dealer_name = req.getParamValue("dealer_name");
			String dealer_id = req.getParamValue("dealer_id");
			List<TtAsWrLabourPricePO> lists = dao.getExistLaborList(user.getCompanyId()) ;
			StringBuffer con = new StringBuffer("\n");
			con.append("select b.dealer_id,b.dealer_code,b.dealer_name ");
			for(int i=0;i<lists.size();i++){
				con.append(",sum(decode(mode_type,'"+lists.get(i).getModeType()+"',labour_price,'')) \""+StringUtil.fmtSpecialStr(lists.get(i).getModeType())+"\"\n");
			}
			con.append("from tt_as_wr_labour_price a,tm_dealer b\n");
			con.append("where a.dealer_id = b.dealer_id and b.status = 10011001 \n"); //yh 2011.2.12
			if(StringUtil.notNull(dealer_name))
				con.append("and b.dealer_name like '%").append(dealer_name).append("%'\n");
			if(StringUtil.notNull(dealer_id))
				con.append("and b.dealer_id in (").append(dealer_id).append(")\n");
			con.append("and a.oem_company_id=").append(user.getCompanyId()).append("\n");
			con.append("group by (b.dealer_id,b.dealer_code,b.dealer_name)\n");
			con.append("order by b.dealer_code\n");
			
			int pageSize = 15 ;
			int curPage = req.getParamValue("curPage") != null ? Integer
					.parseInt(req.getParamValue("curPage")): 1; // 处理当前页
			PageResult<Map<String,Object>> ps = dao.mainQuery(con.toString(), pageSize, curPage) ;
			
			act.setOutData("ps", ps);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 索赔工时单价设定修改页面初始化
	 */
	public void labourPriceUpdateInit(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			String dealerId = req.getParamValue("did");
			
			//经销商信息
			TmDealerPO dpo = new TmDealerPO();
			dpo.setDealerId(Long.parseLong(dealerId));
			List<TmDealerPO> dpoList = dao.select(dpo);
			if(dpoList.size()>0)
				act.setOutData("dealer", dpoList.get(0));
			
			//经销商对应的车型大类单价信息
			TtAsWrLabourPricePO po = new TtAsWrLabourPricePO();
			po.setDealerId(Long.parseLong(dealerId));
			List<TtAsWrLabourPricePO> lists = dao.select(po);
			act.setOutData("lists", lists);
			
			act.setForword(UPDATE_URL);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定->修改");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 根据经销商与车型大类删除相应的数据
	 */
	public void laborPriceDel(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			act.getResponse().setContentType("application/json");
			String dealerId = req.getParamValue("did");
			String modeType = req.getParamValue("modeType");
			String idx = req.getParamValue("idx");
			
			TtAsWrLabourPricePO po = new TtAsWrLabourPricePO();
			po.setDealerId(Long.parseLong(dealerId));
			po.setModeType(modeType);
			dao.delete(po);
			
			act.setOutData("idx", idx);
			act.setOutData("flag", true);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.DELETE_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
			act.setOutData("flag", false);
		}
	}
	
	
	/********************** 微车 **********************/
	
	/*
	 * 主页面初始化
	 */
	public void wcLaborPriceUrl(){
		act = ActionContext.getContext() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			List<AreaProvinceBean> list = dao.getList() ;
			act.setOutData("list",list);
			act.setForword(WC_MAIN_URL);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 主页面主查询
	 */
	public void wcLaborPriceMainQuery(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ;
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			String code = req.getParamValue("groupCode");
			String name = req.getParamValue("groupName");
			StringBuffer con = new StringBuffer() ;
			if(StringUtil.notNull(code))
				con.append(" and lower(a.wrgroup_code) like '%").append(code.toLowerCase()).append("%'\n");
			if(StringUtil.notNull(name))
				con.append(" and a.wrgroup_name like '%").append(name).append("%'\n");
			
			int pageSize = 30 ;
			int curPage = req.getParamValue("curPage") != null ? 
					Integer.parseInt(req.getParamValue("curPage")) : 1; // 处理当前页
			PageResult<Map<String,Object>> ps = dao.wcMainQuery(con.toString(), pageSize, curPage) ;
			act.setOutData("ps",ps);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 修改页面初始化
	 */
	public void wcLabourPriceUpdateInit(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ; 
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			String modeType = req.getParamValue("modeType");
			String con = " and a.wrgroup_code = '"+modeType+"'\n" ;
			Map<String,Object> map = dao.wcMainQuery(con,1,1).getRecords().get(0);
			List<AreaProvinceBean> list = dao.getList() ;
			act.setOutData("map",map);
			act.setOutData("list",list);
			act.setForword(WC_MODIFY_URL);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	/*
	 * 修改操作
	 */
	public void wcLabourPriceUpdate(){
		act = ActionContext.getContext() ;
		req = act.getRequest() ; 
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			String modeType = req.getParamValue("modeType");
			String con = " and a.wrgroup_code = '"+modeType+"'\n" ;
			Map<String,Object> map = dao.wcMainQuery(con,1,1).getRecords().get(0);
			
			List<AreaProvinceBean> list = dao.getList() ;
			
			String[] js = req.getParamValues("js");
			
			for(int i=0;i<js.length;i++){
				if(!new BigDecimal(js[i]).equals(map.get(list.get(i).getOrgCode()))){
					TtAsWrLabourPricePO po = new TtAsWrLabourPricePO();
					po.setModeType(modeType);
					po.setAreaLevel(list.get(i).getAreaLevel());
					List<TtAsWrLabourPricePO> list2 = dao.select(po);
					TtAsWrLabourPricePO po2 = null ;
					for(int j=0;j<list2.size();j++){
						po2 = list2.get(j) ;
						double d1 = Double.parseDouble(js[i]) ; //现在的单价
						double d2 = po2.getBasicLabourPrice()-d1 ; //差价
						po2.setBasicLabourPrice(d1);  //修改基础价
						po2.setLabourPrice(po2.getLabourPrice()-d2) ; //修改最终价
						po2.setUpdateBy(user.getUserId());
						po2.setUpdateDate(new Date());
						po = new TtAsWrLabourPricePO() ;
						po.setId(po2.getId());
						dao.update(po,po2);
					}
				}
			}
				
			act.setOutData("flag",true);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	public void adjustLaborHoursetpre()
	{
		act = ActionContext.getContext() ;		
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{
			List<PriceAdjustBean>	lvList=dao.getAdjustPrice(String.valueOf(Constant.ADJUST_MODE_TYPE_01));
			List<PriceAdjustBean>	clsList=dao.getAdjustPrice(String.valueOf(Constant.ADJUST_MODE_TYPE_02));			
			act.setOutData("clsList", clsList);
			act.setOutData("lvList", lvList);				
			act.setForword(ADJST_URL);			
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	public void getAdjustById()
	{
		act = ActionContext.getContext() ;
		req = act.getRequest() ; 
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{				
			String id=req.getParamValue("id");
			PriceAdjustBean adjust=dao.getAdjustById(id);
			act.setOutData("adjust", adjust);	
			act.setOutData("lv", Constant.ADJUST_MODE_TYPE_01);
			act.setOutData("cls", Constant.ADJUST_MODE_TYPE_02);
			act.setForword(ADJST_MODIFY_URL);			
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	public void adjustUpdate()
	{
		act = ActionContext.getContext() ;
		req = act.getRequest() ; 
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{				
			String id=req.getParamValue("id");
			String adjustPrice=req.getParamValue("adjustPrice");
			dao.adjustUpdate(id,adjustPrice,user.getUserId());
			adjustLaborHoursetpre();
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}
	
	public void updatePrice()
	{
		act = ActionContext.getContext() ;	
		act.getResponse().setContentType("application/json");
		user = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try{	
			List<TtAsWrLabourPricePO> list=dao.getLabourPrice();
			if(list!=null)
			{
				if(list.size()>0)
				{
					for(int i=0;i<list.size();i++)
					{
						dao.updatePrice(list.get(i),user.getUserId());
					}
				}
			}
			act.setOutData("flag", true);
		} catch(Exception e){
			BizException be = new BizException(act,e,ErrorCodeConstant.UPDATE_FAILURE_CODE, "索赔基本参数设定");
			logger.error(user, be);
			act.setException(be);
		}
	}	
}
